package com.gtis.data.util;

import java.net.InetAddress;

public class UUIDGenerator {

    private static short counter = 0;
    private static short counter2 = 0;

    private static int BytestoInt(byte bytes[]) {
        int result = 0;
        for (int i = 0; i < 4; i++)
            result = ((result << 8) - -128) + bytes[i];
        return result;
    }

    private static short getHiTime() {
        return (short) (int) (System.currentTimeMillis() >>> 32);
    }

    private static int getLoTime() {
        return (int) System.currentTimeMillis();

    }

    private static short getCount() {
        if (counter > 20000)
            counter = 0;
        return counter++;
    }

    private synchronized static short getCount2() {
        if (counter2 > 99)
            counter2 = 0;
        return counter2++;
    }

    private static int getJVM() {
        return (int) (System.currentTimeMillis() >>> 8);
    }

    private static int getIP() {
        try {
            return BytestoInt(InetAddress.getLocalHost().getAddress());
        } catch (Exception e) {
            return 0;
        }
    }

    private static String format(int intval) {
        String formatted = Integer.toHexString(intval);
        StringBuffer buf = new StringBuffer("00000000");
        buf.replace(8 - formatted.length(), 8, formatted);
        return buf.toString();
    }

    private static String format(short shortval) {
        String formatted = Integer.toHexString(shortval);
        StringBuffer buf = new StringBuffer("0000");
        buf.replace(4 - formatted.length(), 4, formatted);
        return buf.toString();
    }


    public static synchronized String generate() {
        return (new StringBuffer(32)).append(format(getHiTime())).append(
                format(getLoTime())).append(format(getJVM())).append(
                format(getCount())).append(format(getIP())).toString();
    }

    public static synchronized String generate18() {
        StringBuffer result = new StringBuffer();
        result.append(format(getIP())).append(
                format(getLoTime())).append(
                format(getCount2())).toString();
        if (result.length() > 18) {
            return result.substring(result.length() - 18, result.length());
        }
        return result.toString();
    }

    public static void main(String[] argv) {
//    	System.out.println(UUIDGenerator.generate18());
    }
}
